package com.hmall.trade.listener;

import com.hmall.api.client.PayClient;
import com.hmall.api.dto.PayOrderDTO;
import com.hmall.trade.constants.MQConstants;
import com.hmall.trade.domain.po.Order;
import com.hmall.trade.service.IOrderService;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@RequiredArgsConstructor
@Component
public class OrderDelayMessageListener {

    private final IOrderService orderService;
    private final PayClient payClient;

    // 监听延时队列(应对pay服务的付完钱发送支付成功消息发不出来这边的情况,15分钟一到就会主动去查自己和pay服务的支付状态,类似兜底)
    //不然库存扣减生成订单后,一直死等pay服务的支付成功消息,导致订单无法正常完成,而且也能把支付失败的订单的库存恢复
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = MQConstants.DELAY_QUEUE_Name),
            exchange = @Exchange( value = MQConstants.delay_Exchage_Name,delayed = "true"),
            key = MQConstants.DELAY_ORDER_KEY
    ))
    public void listenOrderDelayMessage(Long orderId){
        //1.查询本地订单状态
        Order order = orderService.getById(orderId);

        //2.检测本地订单状态,判断是否为已支付
        if (order == null || order.getStatus() != 1){
            //如果订单不存在或者已经支付
            return;
        }

        //3.未支付,需要查询pay服务的支付流水状态
        PayOrderDTO payOrder = payClient.queryPayOrderByBizOrderNo(orderId);

        //4.判断pay服务的支付流水状态是否支付
        if (payOrder != null && payOrder.getStatus() == 3){
            //4.1.已支付,标记订单状态为已支付
            orderService.markOrderPaySuccess(orderId);

        }
        else {
            //4.2.未支付,取消订单,恢复库存
            orderService.cancelOrder(orderId);
        }

    }

}
